package com.nuanshui.heatedloan.baseservice.service;

import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.BaseService;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.dubbo.DubboResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class BaseServiceImpl implements BaseService{
	
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	protected Logger logicLog = LoggerFactory.getLogger("LOGIC");
	
	protected Logger bizErrorLog = LoggerFactory.getLogger("biz_log");

	public void error(String msg) {
		LogUtil.info(bizErrorLog, msg);
		throw new BizException(GlobalErrorCode.UNKNOWN, msg);
	}
	
	public HttpServletRequest getRequest() {
		
		ServletRequestAttributes attr = null;
		try {
			attr = (ServletRequestAttributes) RequestContextHolder
					.currentRequestAttributes();
		} catch (IllegalStateException e) {			
		}
		if(attr == null) return null;
		return attr.getRequest();
	}
    
	public UserAgent getUserAgent() {
		HttpServletRequest request =getRequest();
		if(request == null) return new UserAgent();
		return (UserAgent) request.getAttribute(GlobalParam.USER_AGENT);
	}
	
	protected HttpServletRequest getServletRequest() {
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes();
		return attr.getRequest();
	}
	
	
	public boolean isFromWechat() {
		String channel = getCurrentChannel();
		if(channel == null) return false;
        return "weixin".equals(channel);
    }
	
	/**
	 * 获取微信用户的openId
	 * @author Junyan2015
	 * @date 2016年4月19日 上午9:13:06
	 * @since
	 */
	public String getWechatOpenId() {
		if(isFromWechat()) {
			String openid =  getRequest().getHeader("openid");
			if(openid == null) {
				openid = getRequest().getHeader("openId");
			}
			
			if(openid == null) {
				LogUtil.info(log, "openid为空(来自为新客户端可忽略)");
			}
			
			return openid;
		}else {
			LogUtil.info(log,"该用户访问不来自微信，因此不能获取openid");
		}
		return null;
	}
	
	public DubboResponse success(Object object) {
		DubboResponse dubboResponse = new DubboResponse();
		dubboResponse.setData(object);
		return dubboResponse;
	}

	@Override
	public String getCurrentUserInfo() {
		return null;
	}

	@Override
	public String getCurrentChannel() {
		return getUserAgent().getChannel();
	}

	@Override
	public String getCurrentUserId() {
		return getUserAgent().getUserId();
	}

	@Override
	public String getCurrentOpenId() {
		return getWechatOpenId();
	}
}